package com.example.guiguiapplicatio.fragment.SigningArchives;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.Signing;
import com.example.guiguiapplicatio.fragment.SigningArchives.adapter.SigningArchivesAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.ApiUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.refactor.lib.colordialog.PromptDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SigningArchivesFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ApiUtils apiUtils;

    // TODO: Rename and change types of parameters
    private SigningArchivesAdapter signingArchivesAdapter;
    private LinearLayoutManager manager;
    private String idCard;
    private String mParam2;
    ImageButton servic_back;
    TextView tv_start;
    TextView tv_finish;
    Button reset_btu;
    RecyclerView recyclerView;
    Button comit_btu;
    private Call<ResponseBody<List<Signing>>> Signingcall;

    public SigningArchivesFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PoorFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SigningArchivesFragment newInstance(String param1, String param2) {
        SigningArchivesFragment fragment = new SigningArchivesFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString("idCard");
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_total_detail_contract, container, false);
        servic_back = root.findViewById(R.id.servic_back);
        tv_start = root.findViewById(R.id.tv_start);
        tv_finish = root.findViewById(R.id.tv_finish);
        recyclerView = root.findViewById(R.id.service_list);
        apiUtils = new ApiUtils(getString(R.string.api));
        reset_btu = root.findViewById(R.id.reset_btu);
        comit_btu = root.findViewById(R.id.comit_btu);
        Signingcall = apiUtils.getApi().getAllstateSigning(idCard, tv_start.getText().toString(), tv_finish.getText().toString());
        Signingcall.clone().enqueue(new Callback<ResponseBody<List<Signing>>>() {
            @Override
            public void onResponse(Call<ResponseBody<List<Signing>>> call, Response<ResponseBody<List<Signing>>> response) {
                ResponseBody<List<Signing>> responseBody = response.body();
                if (responseBody != null && responseBody.getData() != null) {
                    List<Signing> signingList = responseBody.getData();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            manager = new LinearLayoutManager(getContext());
                            recyclerView.setLayoutManager(manager);
                            signingArchivesAdapter = new SigningArchivesAdapter(signingList, getContext());
                            recyclerView.setAdapter(signingArchivesAdapter);
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<List<Signing>>> call, Throwable t) {

            }
        });
        servic_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_SigningArchivesFragment_to_recordDetailFragment, bundle);
            }
        });
        tv_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(0, // 显示年
                                1, // 显示月
                                2)
                        .showBackNow(false)
                        .setTitle("选择时间")
                        .setOnChoose("确定", aLong -> {
                            Date selectedDate = new Date(aLong);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                            String formattedDate = sdf.format(selectedDate);
                            tv_start.setText(formattedDate);
                        }).build().show();
            }
        });
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(0, // 显示年
                                1, // 显示月
                                2)
                        .showBackNow(false)
                        .setTitle("选择时间")
                        .setOnChoose("确定", aLong -> {
                            Date selectedDate = new Date(aLong);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                            String formattedDate = sdf.format(selectedDate);
                            tv_finish.setText(formattedDate);
                            Call<ResponseBody<List<Signing>>> Signingcall2 = apiUtils.getApi().getAllstateSigning(idCard, tv_start.getText().toString(), tv_finish.getText().toString());
                            Signingcall2.clone().enqueue(new Callback<ResponseBody<List<Signing>>>() {
                                @Override
                                public void onResponse(Call<ResponseBody<List<Signing>>> call, Response<ResponseBody<List<Signing>>> response) {
                                    ResponseBody<List<Signing>> responseBody = response.body();
                                    if (responseBody != null && responseBody.getData() != null) {
                                        List<Signing> signingList = responseBody.getData();
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                manager = new LinearLayoutManager(getContext());
                                                recyclerView.setLayoutManager(manager);
                                                signingArchivesAdapter = new SigningArchivesAdapter(signingList, getContext());
                                                recyclerView.setAdapter(signingArchivesAdapter);
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody<List<Signing>>> call, Throwable t) {

                                }
                            });
                        }).build().show();
            }
        });
        reset_btu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_finish.setText("");
                tv_start.setText("");
                Signingcall.clone().enqueue(SigningListcallback);
            }
        });
        comit_btu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] items = {"个人签约", "家庭签约"};
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                dialog.setTitle("选择签约类型")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (items[which].toString().equals("个人签约")) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("idCard", idCard);
                                    Navigation.findNavController(v).navigate(R.id.action_SigningArchivesFragment_to_newFileFragment, bundle);
                                } else {
                                    Call<ResponseBody<Signing>> SigningCall = apiUtils.getApi().getByNowServingById(idCard);
                                    SigningCall.clone().enqueue(new Callback<ResponseBody<Signing>>() {
                                        @Override
                                        public void onResponse(Call<ResponseBody<Signing>> call, Response<ResponseBody<Signing>> response) {
                                            ResponseBody<Signing> responseBody = response.body();
                                            if (responseBody != null && responseBody.getData() == null) {
                                                Call<ResponseBody<Object>> objectCall = apiUtils.getApi().getRecordById(idCard);
                                                objectCall.clone().enqueue(new Callback<ResponseBody<Object>>() {
                                                    @Override
                                                    public void onResponse(Call<ResponseBody<Object>> call, Response<ResponseBody<Object>> response) {
                                                        ResponseBody<Object> responseBody1 = response.body();
                                                        JsonObject jsonObject = JsonParser.parseString(responseBody1.getData().toString()).getAsJsonObject();
                                                        JsonElement typeElement = jsonObject.get("type");
                                                        if (String.valueOf(typeElement).equals("0")) {
                                                            getActivity().runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    AlertDialog.Builder dialog = new AlertDialog.Builder(getContext())
                                                                            .setTitle("家庭档案")//设置标题
                                                                            .setMessage("您是否要建立一个家庭")//设置要显示的内容
                                                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                                @Override
                                                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                                                    dialogInterface.dismiss();//销毁对话框
                                                                                }
                                                                            })
                                                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                                @Override
                                                                                public void onClick(DialogInterface dialog, int which) {
                                                                                    Call<Object> objectCall = apiUtils.getApi().addNewFamilyarChives(idCard);
                                                                                    objectCall.clone().enqueue(new Callback<Object>() {
                                                                                        @Override
                                                                                        public void onResponse(Call<Object> call, Response<Object> response) {
                                                                                            if (response.code() == 200) {
                                                                                                getActivity().runOnUiThread(() -> {
                                                                                                    Toast.makeText(getContext(), "创建成功", Toast.LENGTH_LONG).show();
                                                                                                    Bundle bundle = new Bundle();
                                                                                                    bundle.putString("idCard", idCard);
                                                                                                    Navigation.findNavController(v).navigate(R.id.action_SigningArchivesFragment_to_FamilyArchivesFragment, bundle);
                                                                                                });
                                                                                            }
                                                                                        }

                                                                                        @Override
                                                                                        public void onFailure(Call<Object> call, Throwable t) {

                                                                                        }

                                                                                    });
                                                                                }
                                                                            });
                                                                    dialog.show();
                                                                }
                                                            });
                                                        }
                                                        else {
                                                            Bundle bundle = new Bundle();
                                                            bundle.putString("idCard", idCard);
                                                            Navigation.findNavController(v).navigate(R.id.action_SigningArchivesFragment_to_FamilyArchivesFragment, bundle);
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Call<ResponseBody<Object>> call, Throwable t) {

                                                    }
                                                });
                                            } else {
                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        new PromptDialog(getContext())
                                                                .setDialogType(PromptDialog.DIALOG_TYPE_INFO)
                                                                .setAnimationEnable(true)
                                                                .setTitleText("INFO")
                                                                .setContentText("请先解除当前状态的签约才可以进行家庭签约")
                                                                .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                                                    @Override
                                                                    public void onClick(PromptDialog dialog) {
                                                                        dialog.dismiss();
                                                                    }
                                                                }).show();
                                                    }
                                                });
                                            }
                                        }

                                        @Override
                                        public void onFailure
                                                (Call<ResponseBody<Signing>> call, Throwable t) {

                                        }
                                    });
                                }
                            }
                        })
                                .

                        setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog.show();
            }
        });
        return root;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

    Callback<ResponseBody<List<Signing>>> SigningListcallback = new Callback<ResponseBody<List<Signing>>>() {
        @Override
        public void onResponse(Call<ResponseBody<List<Signing>>> call, Response<ResponseBody<List<Signing>>> response) {
            ResponseBody<List<Signing>> responseBody = response.body();
            if (responseBody != null && responseBody.getData() != null) {
                List<Signing> signingList = responseBody.getData();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        manager = new LinearLayoutManager(getContext());
                        recyclerView.setLayoutManager(manager);
                        signingArchivesAdapter = new SigningArchivesAdapter(signingList, getContext());
                        recyclerView.setAdapter(signingArchivesAdapter);
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<ResponseBody<List<Signing>>> call, Throwable t) {

        }
    };
}
